/**
 * @file /src/main_window.cpp
 *
 * @brief Implementation for the qt gui.
 *
 * @date February 2011
 **/
/*****************************************************************************
** Includes
*****************************************************************************/

#include <QtGui>
#include <QMessageBox>
#include <iostream>
#include "speech_server/main_window.hpp"

/*****************************************************************************
** Namespaces
*****************************************************************************/

using namespace Qt;

/*****************************************************************************
** Implementation [MainWindow]
*****************************************************************************/

MainWindow::MainWindow(/*int argc, char** argv,*/ QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class.
    communication_handler=new ComminucationHandler(9876,QHostAddress("192.168.10.112"));
    speechServernode=new SpeechServerNode(communication_handler);
    remoteControl=new RemoteControl(communication_handler);
    recognition_logs=new SpeechRecognitionLog(communication_handler);
}
void MainWindow::Init(int argc, char **argv)
{
    if(!speechServernode->init(argc,argv))
    {
        ShowMessageBox(tr("Speech Server Node failed to run"));
        qDebug()<<"Speech Server Node failed to run";
        QApplication::exit(1);
    }
    //ROS node connections
    QObject::connect(speechServernode,              SIGNAL(Info(QString)),        this,               SLOT( updateLoggingView(QString) )       ,Qt::QueuedConnection);
    QObject::connect(speechServernode,              SIGNAL( rosShutdown() ),            this,               SLOT(on_quit()),Qt::QueuedConnection);
    QObject::connect(this,SIGNAL(closing()),speechServernode,SLOT(quit()),Qt::QueuedConnection);

    //Remote Controller connections
    QObject::connect(this,                           SIGNAL( closing() ),              remoteControl,     SLOT( quit())                           );
    QObject::connect(remoteControl,                 SIGNAL(Log(QString)),    this,               SLOT( updateLoggingView(QString) )  ,Qt::QueuedConnection     );

    //SpeechRecogntionLogsSubscriber connections
    QObject::connect(this,                           SIGNAL( closing() ),              recognition_logs,  SLOT( quit()),Qt::QueuedConnection                        );
    QObject::connect(recognition_logs,              SIGNAL( Log(QString) ),this,               SLOT( updateLoggingView(QString) ) ,Qt::QueuedConnection      );
    QObject::connect(this,SIGNAL(closing()),this,SLOT(on_quit()));

    //    connect(this,SIGNAL(destroyed()),this,SLOT(on_quit()));
    communication_handler->start();

    //
    sleep(1);
    //

    speechServernode->start();
    recognition_logs->start();
    remoteControl->start();

}

MainWindow::~MainWindow()
{

    delete speechServernode;
    delete recognition_logs;
    delete remoteControl;
    delete communication_handler;
}

void MainWindow::on_ping_button_clicked()
{
    remoteControl->pingProgramm();
}

void MainWindow::on_run_button_clicked()
{
    remoteControl->runProgramm();
}

void MainWindow::on_kill_button_clicked()
{
    remoteControl->killProgramm();
}
void MainWindow::on_reset_pc_button_clicked()
{
    remoteControl->ResetComputer();
}

void MainWindow::on_transmit_grammar_button_clicked()
{

    QString grammar_address= QFileDialog::getOpenFileName(this,"Select a grammar file","~/",tr("Xml Files (*.xml)"));
    if(grammar_address.isEmpty())
    {
        QFile file(grammar_address);
        QString grammar_data=QString(file.readAll());
        remoteControl->transmitGrammar(grammar_data.toStdString());
    }

}

void MainWindow::on_rollback_grammar_button_clicked()
{
    remoteControl->rollbackGrammar();
}

void MainWindow::on_load_grammar_button_clicked()
{
    bool ok;
    QString text= QInputDialog::getText(this,"Grammar Loading","Grammar Name",QLineEdit::Normal,QDir::home().dirName(),&ok);
    if(ok && !text.isEmpty())
    {
        speechServernode->loadGrammar(text.toStdString());
    }
}

void MainWindow::on_unload_grammar_button_clicked()
{

    bool ok;
    QString text= QInputDialog::getText(this,"Grammar Unloading","Grammar Name",QLineEdit::Normal,QDir::home().dirName(),&ok);
    if(ok && !text.isEmpty())
    {
        speechServernode->unLoadGrammar(text.toStdString());
    }
}

void MainWindow::on_unload_all_grammars_button_clicked()
{
    speechServernode->unLoadAllGrammar();
}
void MainWindow::on_clear_button_clicked()
{
    logs.clear();
    ui.view_logging->setModel(new QStringListModel(logs));
}
void MainWindow::on_quit()
{
    speechServernode->stop();
    remoteControl->stop();
    recognition_logs->stop();
    QApplication::exit();
}

void MainWindow::on_say_button_clicked()
{    bool ok;
     QString text= QInputDialog::getText(this,"TTS","Quatation",QLineEdit::Normal,"",&ok);
      if(ok && !text.isEmpty())
      {
          speechServernode->say(text.toStdString());
      }
}

void MainWindow::updateLoggingView(QString log)
{
    qDebug()<<log;
    logs.append(log);
    if(logs.count()>200)
        logs.removeFirst();
    ui.view_logging->setModel(new QStringListModel(logs));
    ui.view_logging->scrollToBottom();

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    Q_EMIT closing();
    QMainWindow::closeEvent(event);
}
void MainWindow::ShowMessageBox(QString messge)
{
    QMessageBox mbox(this);
    mbox.setText(messge);
    mbox.exec();
}

